from rest_framework import serializers
from book.models import BookInfo,PeopleInfo


class PeopleSerializer(serializers.Serializer):
    """英雄数据序列化器"""
    id = serializers.IntegerField(label='ID')
    name = serializers.CharField(label='名字')
    password=serializers.CharField(label='密码')
    description = serializers.CharField(label='描述信息')


class BookInfoSerializer(serializers.Serializer):
    """图书数据序列化器"""
    id = serializers.IntegerField(label='ID',required=False)
    name = serializers.CharField(label='名称',max_length=10,min_length=4)
    pub_date = serializers.DateField(label='发布日期')
    readcount = serializers.IntegerField(label='阅读量',max_value=9999)
    commentcount = serializers.IntegerField(label='评论量')
    people = PeopleSerializer(many=True,required=False)

    def validate_readcount(self,value):
        if value<0:
            raise serializers.ValidationError('阅读量不能为负数')
        return value

    def validate(self,data):
        readcount = data.get('readcount')
        commentcount = data.get('commentcount')
        if commentcount <0:
            raise serializers.ValidationError('评论量不能为负数')
        if commentcount>readcount:
            raise serializers.ValidationError('阅读数量不能小于评论数')
        return data

    def create(self, validated_data):
        """新建"""
        return BookInfo.objects.create(**validated_data)

    def update(self, instance, validated_data):
        """更新，instance为要更新的对象实例"""
        instance.name = validated_data.get('name', instance.name)
        instance.pub_date = validated_data.get('pub_date', instance.pub_date)
        instance.readcount = validated_data.get('readcount', instance.readcount)
        instance.commentcount = validated_data.get('commentcount', instance.commentcount)
        instance.save()
        return instance


class PeopleInfoSerializer(serializers.Serializer):
    """英雄数据序列化器"""
    id = serializers.IntegerField(label='ID')
    name = serializers.CharField(label='名字')
    password=serializers.CharField(label='密码')
    description = serializers.CharField(label='描述信息')
    # book_id = serializers.IntegerField(label='书籍id')
    # book = serializers.PrimaryKeyRelatedField(label='书籍id',read_only=True)
    # book = serializers.StringRelatedField()
    book = BookInfoSerializer(required=False)


#################     模型化序列化器        ######################
# class BookInfoModelSerializer(serializers.ModelSerializer):
#
#     class Meta:
#         model = BookInfo
#         # fields = '__all__'
#         fields = ['id','name','pub_date','readcount','commentcount']
#         read_only_fields= ['id']
#         extra_kwargs={
#             'readcount': {'min_value': 0, 'required': True},
#             'commentcount': {'min_value': 0, 'required': True},
#         }


class PeopleInfoModelSerializer(serializers.ModelSerializer):
    book_id = serializers.IntegerField(required=False)
    book = serializers.StringRelatedField()
    class Meta:
        model = PeopleInfo
        fields = ['id', 'book_id','book', 'name', 'password','is_delete']
        extra_kwargs = {
            'password': {'write_only': True},
            'is_delete':{'read_only':True}
        }


class BookInfoModelSerializer(serializers.ModelSerializer):
    people = PeopleInfoModelSerializer(many=True)
    class Meta:
        model = BookInfo
        fields = '__all__'

    def create(self, validated_data):
        people=validated_data.pop('people')

        book=BookInfo.objects.create(**validated_data)

        for person in people:
            PeopleInfo.objects.create(book=book,**person)

        return book